<?php

namespace App\Admin\Requests;

use App\Admin\Models\SystemModel;
use App\Admin\Rules\Options;
use App\Admin\Rules\SystemModelValue;
use App\Admin\Rules\ValidRules;
use App\Admin\Rules\FilterRules;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;

class SystemModelRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        if ($this->route()->getName() == 'admin.system-models.by-import') {
            return [
                'file' => 'required|file',
            ];
        }
        $rules = [
            'type' => 'required|in:'.implode(',', array_keys(SystemModel::$inputTypeMap+SystemModel::$searchTypeMap)),
            'name' => 'required|string|max:50',
            'alias' => 'nullable|string|max:50',
            'slug' => 'required|regex:/^[a-z][a-z_\d]*$/|max:50',
            'value' => 'nullable',
            'desc' => 'nullable|string|max:255',
            'options' => new Options($this->input('type')),
            'validation_rules' => [
                'nullable', new ValidRules(),
            ],
            'filter_rules' => [
                'nullable', 'string', 'max:255', new FilterRules(),
            ],
            'order' => 'integer|between:-9999,9999',
            'parent_id' => 'exists:system_models,id',
            'is_virtual' => 'nullable',
            'search_hide' => 'nullable',
            'list_hide' => 'nullable',
            'form_hide' => 'nullable',
            'detail_hide' => 'nullable',
            'form_disabled' => 'nullable',
            'list_width' => 'nullable',
            'list_fixed' => 'nullable',
            'id' => 'nullable',
        ];
        // 如果是虚拟字段，验证默认值
        if ($this->input('is_virtual')) {
            $rules['value'] = [
                'nullable', 'string', 'max:255', new SystemModelValue($this->input('parent_id')),
            ];
        }
        
        if ($this->isMethod('put')) {
            $rules = Arr::only($rules, $this->keys());
            
        }

        if ($this->post('parent_id') == 0) {
            $rules['parent_id'] = 'nullable';
        }
        
        return $rules;
    }

    public function attributes()
    {
        return [
            'type' => '输入类型',
            'name' => '名称',
            'slug' => '标识',
            'desc' => '描述',
            'options' => '选项',
            'value' => '值',
            'validation_rules' => '验证规则',
            'parent_id' => '父级模型',
            'order' => '排序',
            'file' => '文件',
        ];
    }

    public function messages()
    {
        return [
            'slug.regex' => ':attribute 只能包含数字、小写英文字母和下划线，并且必须以字母开头。',
        ];
    }
}
